package com.ruoyi.yipaiju.controller;

import com.google.common.collect.ImmutableMap;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.ApiResult;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.Builder;
import com.ruoyi.yipaiju.domain.Datacenter;
import com.ruoyi.yipaiju.service.ICommonService;
import com.ruoyi.yipaiju.service.IDatacenterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.temporal.TemporalAdjusters;
import java.util.*;

@RestController
@RequestMapping("/datacenter")
public class DatacenterController extends BaseController {

    @Autowired
    private IDatacenterService datacenterService;
    @Autowired
    private ICommonService commonService;

    @GetMapping("")
    public ApiResult datacenter(Datacenter datacenter) {
        // 获取城市
//        ApiResult address = commonService.getAddress(datacenter.getLatitude(), datacenter.getLongitude());
//        Map<String, String> addressMap = (Map<String, String>) address.get(ApiResult.DATA_TAG);

        String province = ""; //addressMap.get("province");
        String city = ""; //addressMap.get("city");
        String district = ""; //addressMap.get("district");
        String beginTime = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, DateUtils.addDays(new Date(), -7));

//        Map<String, String> where = new HashMap<>();
//        where.put("beginTime", beginTime);
//        where.put("province", province);
//        where.put("city", city);
//        where.put("district", district);
        List<Map<String, String>> timeList = datacenterService.dayAddedCount(datacenter);
        Map<String, String> timeMap = new HashMap<>();
        timeList.stream().forEach(item -> { timeMap.put(item.get("day_time"), item.get("day_count")); });
        List<Map<String, Object>> keyasArray = new ArrayList<>();
        for (int i = 7; i >= 1; i--) {
            String currTime = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, DateUtils.addDays(new Date(), -i));
            Map<String, Object> keyasMap = new HashMap<>();
            keyasMap.put("key_as_string", currTime);
            keyasMap.put("doc_count", timeMap.get(currTime) == null ? 0 : timeMap.get(currTime));
            keyasArray.add(keyasMap);
        }

        //aggs_today.deal_today.doc_count       今日成交
        //added_today.doc_count                 今日新增
        //aggs_today.failed_today.doc_count     今日流拍
        //participants.no_participant.doc_count 今日预约

        //今日新增
        int added_today_doc_count = datacenterService.dayAddedCountForeclosed(Builder.of(Datacenter::new)
                .with(Datacenter::setDate, DateUtils.getDate())
                .with(Datacenter::setProvince, province)
                .with(Datacenter::setCity, city)
                .with(Datacenter::setDistrict, district)
                .build());

        //今日预约
        int participants_no_participant_doc_count = datacenterService.dayAddedBooking(null);

        // 今日成交
        int added_today_deal_count = datacenterService.dayAddedCountForeclosed(Builder.of(Datacenter::new)
                .with(Datacenter::setDate, DateUtils.getDate())
                .with(Datacenter::setProvince, province)
                .with(Datacenter::setCity, city)
                .with(Datacenter::setDistrict, district)
                .with(Datacenter::setStatus, "已成交")
                .build());

        // 今日流拍
        int added_today_failed_count = datacenterService.dayAddedCountForeclosed(Builder.of(Datacenter::new)
                .with(Datacenter::setDate, DateUtils.getDate())
                .with(Datacenter::setProvince, province)
                .with(Datacenter::setCity, city)
                .with(Datacenter::setDistrict, district)
                .with(Datacenter::setStatus, "已流拍")
                .build());

        return ApiResult.success(ImmutableMap.of("aggregations",
                ImmutableMap.of("aggs_today", ImmutableMap.of("deal_today", ImmutableMap.of("doc_count", added_today_deal_count), "failed_today", ImmutableMap.of("doc_count", added_today_failed_count)),
                        "added_today", ImmutableMap.of("doc_count", added_today_doc_count),
                        "participants", ImmutableMap.of("no_participant", ImmutableMap.of("doc_count", participants_no_participant_doc_count)),
                        "aggs_week", ImmutableMap.of("dayOfWeek", ImmutableMap.of("buckets", keyasArray))),
                "local", ImmutableMap.of("province", province, "city", city, "district", district) ));
    }


    @GetMapping("/week_summary")
    public ApiResult week_summary(Datacenter datacenter) {

        String beginDate = datacenter.getBeginDate();
        // 获取当前周的日期
        if (StringUtils.isEmpty(datacenter.getBeginDate()) || StringUtils.isEmpty(datacenter.getEndDate())){
            LocalDate currentDate = LocalDate.now();
            LocalDate previousSunday = currentDate.with(TemporalAdjusters.previous(DayOfWeek.SUNDAY));
            LocalDate previousMonday = previousSunday.minusDays(6);
            datacenter.setBeginDate(previousMonday.toString());
            datacenter.setEndDate(previousSunday.minusDays(-1).toString());
            datacenter.setEndDate1(previousSunday.toString());
            beginDate = previousMonday.toString();
        }

        int total_count = datacenterService.queryCountByStatus(datacenter);
        // 在线
        datacenter.setStatus("'预告中', '进行中'");
        int online_count = datacenterService.queryCountByStatus(datacenter);
        // 上拍
        datacenter.setStatus("'进行中'");
        int auction_count = datacenterService.queryCountByStatus(datacenter);
        // 成交量
        datacenter.setStatus("'已成交'");
        int deal_count = datacenterService.queryCountByStatus(datacenter);
        // 成交率
        int deal_rate = total_count == 0 ? 0 : new BigDecimal(deal_count).divide(new BigDecimal(total_count), 2, RoundingMode.HALF_UP).multiply(new BigDecimal(100)).intValue();

        datacenter.setStatus(null);
        // 评估价
        Map<String, String> estimateMap = datacenterService.queryEstimatePrice(datacenter);
        String estimateAvgPrice = estimateMap.containsKey("estimate_price_yuan_avg")?String.valueOf(estimateMap.get("estimate_price_yuan_avg")):"";
        BigDecimal estimate_avg = new BigDecimal(0);
        if (StringUtils.isNotEmpty(estimateAvgPrice)){
            estimate_avg = new BigDecimal(estimateAvgPrice);
        }
        // 成交价
        Map<String, String> dealMap = datacenterService.queryDealPrice(datacenter);
        String dealAvgPrice = dealMap.containsKey("deal_price_avg")?String.valueOf(dealMap.get("deal_price_avg")):"";
        BigDecimal deal_avg = new BigDecimal(0);
        if (StringUtils.isNotEmpty(dealAvgPrice)){
            deal_avg = new BigDecimal(dealAvgPrice);
        }
        // 起拍价
        Map<String, String> startMap = datacenterService.queryStartPrice(datacenter);
        String startAvgPrice = startMap.containsKey("price_yuan_avg")?String.valueOf(startMap.get("price_yuan_avg")):"";
        BigDecimal start_avg = new BigDecimal(0);
        if (StringUtils.isNotEmpty(startAvgPrice)){
            start_avg = new BigDecimal(startAvgPrice);
        }
        // 围观 订阅
        Map<String, String> browseMap = datacenterService.queryBrowseCount(datacenter);
        String browse_count_avg = "0";
        String subscriber_count_avg = "0";
        if (browseMap != null){
            browse_count_avg = browseMap.containsKey("browse_count_avg")?String.valueOf(browseMap.get("browse_count_avg")):"0";
            subscriber_count_avg = browseMap.containsKey("subscriber_count_avg")?String.valueOf(browseMap.get("subscriber_count_avg")):"0";
        }

        // 折扣率  成交价/评估价
        int dicount_rate = estimate_avg.compareTo(new BigDecimal(0)) == 0 ? 0 : deal_avg.divide(estimate_avg, 2, RoundingMode.HALF_UP).multiply(new BigDecimal(100)).intValue();
        // 溢价率  （成交价-起拍价）/起拍价
        int premium_rate = start_avg.compareTo(new BigDecimal(0)) == 0 ? 0 : (deal_avg.subtract(start_avg)).divide(start_avg, 2, RoundingMode.HALF_UP).multiply(new BigDecimal(100)).intValue();


        // ---------------------曲线
        datacenter.setStatus("'进行中'");
        List<Map<String, String>> auctionList = datacenterService.dayAddedCount(datacenter);
        datacenter.setStatus("'已成交'");
        List<Map<String, String>> dealList = datacenterService.dayAddedCount(datacenter);

        Map<String, String> auctionMap11 = new HashMap<>();
        auctionList.stream().forEach(item -> { auctionMap11.put(item.get("day_time"), item.get("day_count")); });

        Map<String, String> dealMap11 = new HashMap<>();
        dealList.stream().forEach(item -> { dealMap11.put(item.get("day_time"), item.get("day_count")); });

        List<Map<String, Object>> keyasArray = new ArrayList<>();
        for (int i = 0; i < 7; i++) {
            String currTime = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, DateUtils.addDays(DateUtils.parseDate(beginDate), i));
            Map<String, Object> keyasMap = new HashMap<>();
            keyasMap.put("key_as_string", currTime);
            keyasMap.put("auction_count", auctionMap11.get(currTime) == null ? 0 : auctionMap11.get(currTime));
            keyasMap.put("deal_count", dealMap11.get(currTime) == null ? 0 : dealMap11.get(currTime));
            keyasArray.add(keyasMap);

        }

        Map<String, Object> map1 = new HashMap<>();
        map1.put("total_count", total_count);
        map1.put("online_count", online_count);
        map1.put("auction_count", auction_count);
        map1.put("deal_count", deal_count);
        map1.put("deal_rate", deal_rate);
        map1.put("estimate_avg", estimate_avg);
        map1.put("deal_avg", deal_avg);
        map1.put("start_avg", start_avg);
        map1.put("browse_count_avg", browse_count_avg);
        map1.put("subscriber_count_avg", subscriber_count_avg);
        map1.put("dicount_rate", dicount_rate);
        map1.put("premium_rate", premium_rate);
        map1.put("beginDate", DateUtils.parseDateToStr("MM.dd", DateUtils.parseDate(datacenter.getBeginDate())));
        map1.put("endDate", DateUtils.parseDateToStr("MM.dd", DateUtils.parseDate(datacenter.getEndDate1())));

        Map<String, Object> map2 = new HashMap<>();
        map2.put("province", datacenter.getProvince());
        map2.put("city", datacenter.getCity());
        map2.put("district", datacenter.getDistrict());

        return ApiResult.success(ImmutableMap.of("argsWeek", map1,
                "local", map2,
                "buckets", keyasArray));
    }

    @GetMapping("/week_info")
    public ApiResult week_info(Datacenter datacenter) {

        String beginDate = datacenter.getBeginDate();
        // 获取当前周的日期
        if (StringUtils.isEmpty(datacenter.getBeginDate()) || StringUtils.isEmpty(datacenter.getEndDate())){
            LocalDate currentDate = LocalDate.now();
            LocalDate previousSunday = currentDate.with(TemporalAdjusters.previous(DayOfWeek.SUNDAY));
            LocalDate previousMonday = previousSunday.minusDays(6);
            datacenter.setBeginDate(previousMonday.toString());
            datacenter.setEndDate(previousSunday.minusDays(-1).toString());
            datacenter.setEndDate1(previousSunday.toString());
            beginDate = previousMonday.toString();
        }

        datacenter.setStatus("'进行中'");
        List<Map<String, String>> auctionList = datacenterService.dayAddedCount(datacenter);
        datacenter.setStatus("'已成交'");
        List<Map<String, String>> dealList = datacenterService.dayAddedCount(datacenter);

        Map<String, String> auctionMap = new HashMap<>();
        auctionList.stream().forEach(item -> { auctionMap.put(item.get("day_time"), item.get("day_count")); });

        Map<String, String> dealMap = new HashMap<>();
        dealList.stream().forEach(item -> { dealMap.put(item.get("day_time"), item.get("day_count")); });

        List<Map<String, Object>> keyasArray = new ArrayList<>();
        for (int i = 0; i < 7; i++) {
            String currTime = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, DateUtils.addDays(DateUtils.parseDate(beginDate), i));
            Map<String, Object> keyasMap = new HashMap<>();
            keyasMap.put("key_as_string", currTime);
            keyasMap.put("auction_count", auctionMap.get(currTime) == null ? 0 : auctionMap.get(currTime));
            keyasMap.put("deal_count", dealMap.get(currTime) == null ? 0 : dealMap.get(currTime));
            keyasArray.add(keyasMap);

        }
        return ApiResult.success(keyasArray);

    }

    public static void main(String[] args) {
        LocalDate currentDate = LocalDate.now();

        LocalDate previousSunday = currentDate.with(TemporalAdjusters.previous(DayOfWeek.SUNDAY));
        LocalDate previousMonday = previousSunday.minusDays(6);

        System.out.println("上周日期范围：" + previousMonday + " - " + previousSunday.minusDays(-1));
    }
}
